package com.codesuc.aichat.aiAgent.controller;

import com.codesuc.aichat.aiAgent.config.AIConfig;
import com.codesuc.aichat.aiAgent.factory.AIServiceFactory;
import com.codesuc.aichat.aiAgent.request.ChatRequest;
import com.codesuc.aichat.aiAgent.request.Message;
import com.codesuc.aichat.aiAgent.response.ChatResponse;
import com.codesuc.aichat.aiAgent.strategy.AIService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Collections;

/**
 * @Author: ZhangGongMing
 * @CreateTime: 2025/9/24 09:50
 * @description: AI 服务控制层
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/v1/aiAgent")
@Tag(name = "AIAgentController", description = "AIAgent控制层")
public class AIAgentController {

    @Autowired
    private AIServiceFactory factory;
    @Autowired
    private AIConfig config;

    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(summary = "AI 聊天", description = "AI 聊天")
    public Flux<ChatResponse> chat(@RequestBody ChatRequest request) {
        AIService aiService = factory.getAIService(config.getProvider());
        return aiService.chat(request);
    }

    @PostMapping(value = "/chatAudio")
    @Operation(summary = "AI 语音聊天", description = "AI 语音聊天")
    @CrossOrigin
    public Flux<ChatResponse> chatAudio(@RequestParam Long roleId) {
        AIService aiService = factory.getAIService(config.getProvider());
        String text = aiService.audioASR();
        ChatRequest request = new ChatRequest();
        Message message = new Message();
        message.setRole("user");
        message.setContent(text);
        request.setMessageList(Collections.singletonList(message));
        request.setRoleId(roleId);
        request.setIsStream(false);
        return aiService.chat(request).doOnNext(chatResponse -> {
            if (chatResponse.getContent() != null) {
                aiService.audioTTS(chatResponse.getContent(), roleId);
            }
        });
    }

    @PostMapping(value = "/audioASR")
    @Operation(summary = "音频转文字", description = "音频转文字")
    @CrossOrigin
    public String audioASR() {
        AIService aiService = factory.getAIService(config.getProvider());
        return aiService.audioASR();
    }

    @PostMapping(value = "/stopAudioASR")
    @Operation(summary = "停止音频转文字", description = "停止音频转文字")
    @CrossOrigin
    public void stopAudioASR() {
        AIService aiService = factory.getAIService(config.getProvider());
        aiService.stopAudioASR();
    }

}
